<?php
/**
 * 汽车服务项目
 * Created by PhpStorm.
 * User: andy
 * Date: 2019/11/19
 * Time: 下午6:42
 */

namespace app\common\model;

use think\facade\Cache;
use think\Model;
use think\Db;
class UserCarModel extends Model
{
    const NO_STATUS = 2; //拒绝
    const SHOW_STATUS = 1; //通过审核
    const HIDE_STATUS = 0; //审核中
    const DEL_STATUS = -1; //删除

    const SELL_STATUS_DEL = -1; //删除
    const SELL_STATUS_NO = 0; //未售
    const SELL_STATUS_OK = 1; //已售

    protected $autoWriteTimestamp = true;

    public function user()
    {
        return $this->hasOne('MemberModel', 'uid', 'user_id')->field('uid,mobile');
    }

    public function car()
    {
        $field='car_id,series_thumb,car_name,car_pl_l,car_bsxlx,car_hbbz,series_max,car_zczdlx,car_tyjcgn';
        $field.=',car_abs,car_bxhz,car_dphj,car_zdzc,car_sphz,car_qhld,car_ba,car_gyhbx,car_wysqd,car_wysjr';
        return $this->hasOne('CarModel', 'car_id', 'car_id')->cache(true)->field($field);
    }

    /**
     * 所有通过车
     * @param array $where
     * @param int $pageSum
     * @return \think\Paginator
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getALL($where = [], $pageSum = 0)
    {
        if ($pageSum <= 0) {
            $pageSum = getSystem("pageSUM") ? getSystem("pageSUM") : 10;
        }

        $list = self::where('status', self::SHOW_STATUS)
            ->with('user')
            ->where($where)
            ->order("create_time desc")
            ->paginate($pageSum);

        foreach ($list as $vo) {
            $brand = CarBrandModel::field("brand")->where('brand_id', $vo->brand_id)->find();
            $series = CarSeriesModel::field('series_name')->where('series_id', $vo->series_id)->find();
            if(!empty($vo->vin)){
                $carVin=CarLicenseMoreModel::field("sale_name,guiding_price")->where('vin','=',$vo->vin)->find();
                $vo->car_name = $carVin->sale_name;
                $vo->series_max = $carVin->guiding_price."万";
            }else{
                if($vo->car_id){
                    $car = CarModel::field('car_name,series_max,car_case')->where('car_id',$vo->car_id)->find();
                    $vo->car_name = $car->car_name;
                    $vo->series_max = $car->series_max;
                }
            }


            $vo->brand_name = $brand->brand;
            $vo->series_name = $series->series_name;

            $startdate=time();
            $enddate=$vo->publish_time-$startdate;

            if($enddate<=0){
                $vo->status='已通过';
            }else{

                $date=floor($enddate/86400);
                $hour=floor($enddate%86400/3600);
                $minute=floor($enddate%86400/60);
                $second=floor($enddate%86400%60);

                $str='';
                if($date>0) $str.=$date."天后发布";
                else if($hour>0) $str.=$hour."小时后发布";
                else if($minute>0) $str.=$minute."分钟后发布";
                else if($second>0) $str.=$second."秒后发布";

                $vo->status=$str;
            }
        }

        return $list;
    }

    /**
     * 所有待审核车
     * @param array $where
     * @param int $pageSum
     * @return \think\Paginator
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getWaitCar($where = [], $pageSum = 0)
    {
        if ($pageSum <= 0) {
            $pageSum = getSystem("pageSUM") ? getSystem("pageSUM") : 10;
        }

        $list = self::where('status', 'in', [self::HIDE_STATUS, self::NO_STATUS])
            ->with('user')
            ->where($where)
            ->order('status asc,create_time desc')
            ->paginate($pageSum);

        foreach ($list as $vo) {
            $brand = CarBrandModel::field("brand")->where('brand_id', $vo->brand_id)->find();
            $series = CarSeriesModel::field('series_name')->where('series_id', $vo->series_id)->find();

            if(!empty($vo->vin)){
                $carVin=CarLicenseMoreModel::field("sale_name,guiding_price")->where('vin','=',$vo->vin)->find();
                $vo->car_name = $carVin->sale_name;
                $vo->series_max = $carVin->guiding_price."万";
            }else{
                if($vo->car_id){
                    $car = CarModel::field('car_name,series_max,car_case')->where('car_id',$vo->car_id)->find();
                    $vo->car_name = $car->car_name;
                    $vo->series_max = $car->series_max;
                }
            }

            $vo->brand_name = $brand->brand;
            $vo->series_name = $series->series_name;

        }

        return $list;
    }

    /**
     * 获取导出数据
     * @param array $where
     * @return array|\PDOStatement|string|\think\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public static function getSelect($where = [])
    {
        $list = self::with('user')
            ->where('status', '>', self::DEL_STATUS)
            ->where($where)
            ->select();

        foreach ($list as $vo) {
            $brand = CarBrandModel::field("brand")->where('brand_id', $vo->brand_id)->find();
            $series = CarSeriesModel::field('series_name')->where('series_id', $vo->series_id)->find();
            $car = CarModel::field('car_name,series_max,car_case')->where('car_id',$vo->car_id)->find();

            $vo->brand_name = $brand->brand;
            $vo->series_name = $series->series_name;

            $vo->car_name="";
            $vo->series_max="";
            $vo->car_case="";
            if(!empty($car)){
                $vo->car_name=$car->car_name;
                $vo->series_max=$car->series_max;
                $vo->car_case=$car->car_case;
            }
        }

        return $list;
    }


    /**
     * 删除
     * @param $id
     * @return array
     */
    public function del($id)
    {

        $au = self::get($id);
        $au->status = self::DEL_STATUS;

        UserCarMessageModel::where('user_car_id',$id)->update(['status'=>-1]);
        UserCollectModel::where('user_car_id',$id)->delete();

        $status = $au->save();
        if ($status) {
            return ['status' => 1, 'msg' => '删除成功！'];
        } else {
            return ['status' => 0, 'msg' => '删除失败！'];
        }
    }

    /**
     * 增加
     * @param $data
     * @return array
     * @throws \think\exception\DbException
     */
    public function adds($data)
    {

        if (empty($data['id'])) {
            $status = self::insertGetId($data);

            if ($status) {
                $car=self::get($status);
                $num=date("Ymd").str_pad(mt_rand(10,999),3,"0",STR_PAD_BOTH);
                $car->car_number=$num;
                $car->save();


                return ['status' => 1, 'msg' => '增加成功！',"id"=>$status];
            } else {
                return ['status' => 0, 'msg' => '增加失败！'];
            }
        } else {
            $status = self::save($data, ['id' => $data["id"]]);

            if ($status) {
                return ['status' => 1, 'msg' => '修改成功！'];
            } else {
                return ['status' => 0, 'msg' => '修改失败！'];
            }
        }

    }

    /**
     * 所有通过车
     * @param array $where
     * @param int $pageSum
     * @return \think\Paginator
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getUserCar($where = [], $pageSum = 0,$isData=false)
    {
        if ($pageSum <= 0) {
            $pageSum = getSystem("pageSUM") ? getSystem("pageSUM") : 10;
        }

        $list = self::where('status', self::SHOW_STATUS)
            ->where($where)
            ->where('publish_time', '<=',time())
            ->order('good_numb desc,msg_count desc,refresh_time desc,adopt_time desc,hot desc')
            ->paginate($pageSum);

        $data=[];

        $field='car_id,series_thumb,car_name,car_pl_l,car_bsxlx,car_hbbz,series_max,car_zczdlx,car_tyjcgn';
        //$field.=',car_abs,car_bxhz,car_dphj,car_zdzc,car_sphz,car_qhld,car_ba,car_gyhbx,car_wysqd,car_wysjr';
//        return $this->hasOne('CarModel', 'car_id', 'car_id')->cache(true)->field($field);

        foreach ($list as $item){
            $item->series=CarSeriesModel::field('series_name,thumb')->where('series_id', $item->series_id)->find();

            $item->img_list=json_decode($item->img_list,true);

            if(!empty($item->vin)){
                $carVin=CarLicenseMoreModel::field("sale_name,brand_name")->where('vin','=',$item['vin'])->find();
                $item->series['series_name']=$carVin['brand_name']." ".$carVin['sale_name'];
            }else{
                $item->car=CarModel::field($field)->where('car_id',$item->car_id)->find();
            }

            $item->collectCount=UserCollectModel::field("id")
                ->where('user_car_id',$item->id)
                ->where("status",UserCollectModel::SHOW_STATUS)
                ->count();

            $item->msgCount=UserCarMessageModel::field("id")
                ->where('user_car_id',$item->id)
                ->where("status",UserCarMessageModel::SHOW_STATUS)
                ->count();

            $data[]=$item;
        }

        if(!$isData) return $list;

        return $data;
    }

    /**
     * 获取详情
     * @param $id
     * @return null|\think\db\Query
     * @throws \think\Exception\DbException
     */
    public function details($id,$ip)
    {
        $info = self::with("car")
            ->cache(true)
            ->get($id);

        $t = Cache::get($ip . "_car_".$id);
        if (empty($t)) {
            $info->look_num=$info->look_num+1;
            $info->save();
            Cache::set($ip . "_car_".$id, time(), 60 * 60 * 24);
        }

        if (!empty($t) && (time() - $t) > (60 * 60 * 24)) {
            $info->look_num=$info->look_num+1;
            $info->save();
            Cache::set($ip . "_car_".$id, time(), 60 * 60 * 24);
        }
        $info->base_img="";
        if(empty($info->img_list)){
            $info->img_list=[];
        }else{
            $info->img_list=json_decode($info->img_list,true);
        }

        if(empty($info->add_conf)){
            $info->add_conf=[];
        }else{
            $cArr=json_decode($info->add_conf,true);
            $info->add_conf=CarLabelModel::field("id,title,thumb")
            ->where('id','in',$cArr)
            ->where('status',CarLabelModel::SHOW_STATUS)
            ->order('list_order asc')
            ->select();
        }

        //首付30%
        $payment=round($info->price*0.3,1);
        //转换为万为单位
        $have=($info->price-$payment)*10000;
        //计算月供
        $huan=$have/36;
        $rate=($have*0.0435)*3/36;
        $month=round($huan+$rate,2);



        $info->jr=[
            "payment"=>$payment,
            "month"=>$month,
            "phone"=>getSystem("server_phone"),
        ];

        return $info;
    }

    public function getMyRelease($where = [], $pageSum = 0){
        if ($pageSum <= 0) {
            $pageSum = getSystem("pageSUM") ? getSystem("pageSUM") : 10;
        }
        $list = self::where('status', ">=",0)
            ->where($where)
            ->order('refresh_time desc,create_time desc')
            ->paginate($pageSum);

        $checkDayStr = date('Y-m-d ',time());
        $timeBegin = strtotime($checkDayStr."00:00".":00");
        $timeEnd = strtotime($checkDayStr."23:59".":59");

        $field='car_id,series_thumb,car_name,car_pl_l,car_bsxlx,car_hbbz,series_max,car_zczdlx,car_tyjcgn';
        foreach ($list as $item){
            $item->series=CarSeriesModel::field('series_name,thumb')->where('series_id', $item->series_id)->find();
            $item->img_list=json_decode($item->img_list,true);
            $item->refresh_status=false;

            if(!empty($item['vin'])){
                $carVin=CarLicenseMoreModel::field("sale_name")->where('vin','=',$item->vin)->find();
                $item->series['series_name']=$carVin['sale_name'];
            }else{
                $item->car=CarModel::field($field)->where('car_id',$item->car_id)->find();
            }

//            $checkTime=$item->refresh_time;
//
//            if($checkTime >= $timeBegin && $checkTime <= $timeEnd)
//            {
//                $item->refresh_status=true;
//            }
        }

        return $list;
    }

    public function upLastTime($id){
        $lastReplyTime = time();
        $res = $this->update(["lastreply_time"=>$lastReplyTime,"id"=>$id]);
        return $res;
    }
} 